package com.zmcn.fileTransfer.fw.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * 简单加解密
 * 
 * @author 欧建东
 * @email oyjd@163.com
 * 
 */
public class SecurityUtil {
	public static void main(String[] args) {
		System.out.println(encoderByMd5("123456"));
	}

	/**
	 * MD5加BASE64加密
	 * 
	 * @param str
	 * @return
	 */
	public static String encoderByMd5(String str) {
		MessageDigest md5 = null;
		String newstr = null;
		try {
			md5 = MessageDigest.getInstance("MD5");// MD5
			BASE64Encoder base64en = new BASE64Encoder();
			newstr = base64en.encode(md5.digest(str.getBytes("utf-8")));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return newstr;
	}

	/**
	 * BASE64加密
	 * 
	 * @param str
	 * @return String
	 * @throws IOException
	 */
	public static String encodeString(String str) throws IOException {
		BASE64Encoder encoder = new BASE64Encoder();
		String encodedStr = new String(encoder.encodeBuffer(str.getBytes()));
		return encodedStr.trim();
	}

	/**
	 * BASE64解密
	 * 
	 * @param str
	 * @return String
	 * @throws IOException
	 */
	public static String decodeString(String str) throws IOException {
		BASE64Decoder dec = new BASE64Decoder();
		String value = new String(dec.decodeBuffer(str));
		return value;
	}

}
